const express = require('express')
const jwt = require('jsonwebtoken')

let checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware')
const router = express.Router()
const monent = require('moment')
const AccountModel = require('../../models/AccountModel')

router.get('/account', checkTokenMiddleware, function (req, res, next) {
  console.log(req.user)
  AccountModel.find()
    .sort({ time: -1 })
    .then((data) => {
      res.json({
        code: '0000',
        msg: '读取成功',
        data
      })
    })
    .catch((err) => {
      res.json({
        code: '1001',
        msg: '读取失败...',
        data: null
      })
    })
})

router.post('/account', checkTokenMiddleware, function (req, res, next) {
  AccountModel.create({
    ...req.body,
    time: monent(req.body.time).toDate()
  })
    .then((data) => {
      res.json({
        code: '0000',
        msg: '创建成功',
        data
      })
    })
    .catch((err) => {
      res.json({
        code: '1002',
        msg: '创建失败了...',
        data: null
      })
    })
})

router.delete('/account/:id', checkTokenMiddleware, function (req, res, next) {
  let _id = req.params.id
  AccountModel.deleteOne({ _id })
    .then((data) => {
      res.json({
        code: '0000',
        msg: '删除成功',
        data: null
      })
    })
    .catch((err) => {
      res.json({
        code: '1003',
        msg: '删除账单失败',
        data: null
      })
    })
})

router.get('/account/:id', checkTokenMiddleware, (req, res) => {
  let { id } = req.params
  AccountModel.findById(id)
    .then((data) => {
      res.json({
        code: '0000',
        msg: '读取成功...',
        data
      })
    })
    .catch((err) => {
      res.json({
        code: '1004',
        msg: '读取失败....',
        data: null
      })
    })
})

router.patch('/account/:id', checkTokenMiddleware, (req, res) => {
  let { id } = req.params
  AccountModel.updateOne({ _id: id }, req.body)
    .then((data) => {
      AccountModel.findById(id)
        .then((data) => {
          res.json({
            code: '0000',
            msg: '更新成功...',
            data
          })
        })
        .catch((err) => {
          res.json({
            code: '1004',
            msg: '读取失败....',
            data: null
          })
        })
    })
    .catch((err) => {
      res.json({
        code: '1005',
        msg: '更新失败....',
        data: null
      })
    })
})

module.exports = router
